package com.icongyou.enterprise.data_aggregation.service.impl;

import com.icongyou.enterprise.common.result.PageResult;
import com.icongyou.enterprise.data_aggregation.entity.*;
import com.icongyou.enterprise.data_aggregation.mapper.DataAggregationMapper;
import com.icongyou.enterprise.data_aggregation.service.DataAggregationService;
import com.icongyou.enterprise.talent_pool.entity.vo.CoreSubmissionVO;
import lombok.RequiredArgsConstructor;
import org.apache.catalina.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.stream.Collectors;

import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class DataAggregationServiceImpl implements DataAggregationService {

    private final DataAggregationMapper dataAggregationMapper;

    @Override
    public UserEntity getUserByAccount(String account) {
        // 根据账号查询用户信息
        return dataAggregationMapper.getUserByAccount(account);
    }

    @Override
    public String selectTenantIdByName(String tenantName) {
        return dataAggregationMapper.selectTenantIdByName(tenantName);
    }

    @Override
    public Integer validateUserTenant(String userId, String tenantId) {
        return dataAggregationMapper.validateUserTenant(userId,tenantId);
    }

    @Override
    public int insertUser(UserEntity user) {
        // 插入新用户记录
        return dataAggregationMapper.insertUser(user);
    }

    @Override
    public int updateUserLastLoginTime(String userId, LocalDateTime loginTime) {
        // 更新用户最后登录时间
        return dataAggregationMapper.updateUserLastLoginTime(userId, loginTime);
    }

    @Override
    public List<UserEntity> getStudentByCondition(Map<String, Object> condition) {
        // 根据条件查询学生列表
        return dataAggregationMapper.getStudentByCondition(condition);
    }

    @Override
    public UserEntity getStudentById(String studentId) {
        // 根据学生ID查询学生信息
        return dataAggregationMapper.getStudentById(studentId);
    }

    public UserEntity getUserById(String userId){
        return dataAggregationMapper.getUserById(userId);
    }

    @Override
    public List<CourseStudentEntity> getStudentCourse(String studentId) {
        // 查询学生选课信息
        return dataAggregationMapper.getStudentCourse(studentId);
    }

    @Override
    public CourseProgressEntity getStudentCourseProgress(String studentId, String courseId) {
        // 查询学生在特定课程中的进度信息
        return dataAggregationMapper.getStudentCourseProgress(studentId, courseId);
    }

    @Override
    public List<AssignmentStudentEntity> getStudentAssignmentScore(String studentId, String courseId) {
        // 查询学生在特定课程中的任务成绩
        return dataAggregationMapper.getStudentAssignmentScore(studentId, courseId);
    }

    @Override
    public List<SubmissionEntity> getStudentSubmission(String studentId, String assignmentId) {
        // 查询学生对特定任务的提交记录
        return dataAggregationMapper.getStudentSubmission(studentId, assignmentId);
    }

    @Override
    public List<GradeEntity> getStudentGrade(String submissionId) {
        // 查询提交作品的批改信息
        return dataAggregationMapper.getStudentGrade(submissionId);
    }

    @Override
    public List<CourseStudentEntity> getCourseRanking(String courseId) {
        // 查询课程中学生排名
        return dataAggregationMapper.getCourseRanking(courseId);
    }

    @Override
    public List<TeamMemberEntity> getStudentTeam(String studentId) {
        // 查询学生所属团队信息
        return dataAggregationMapper.getStudentTeam(studentId);
    }

    @Override
    public TeamEntity getTeamById(String teamId) {
        // 根据团队ID查询团队信息
        return dataAggregationMapper.getTeamById(teamId);
    }

    @Override
    public String getStudentCompetencyLevel(String studentId, String courseId) {
        // 查询学生在课程中的能力维度达成度
        return dataAggregationMapper.getStudentCompetencyLevel(studentId, courseId);
    }

    @Override
    public List<GradeEntity> getTeacherComment(String studentId) {
        // 查询教师对学生的评语
        return dataAggregationMapper.getTeacherComment(studentId);
    }

    @Override
    public Map<String, Object> getStudentRawMetrics(String studentId, Double passThreshold, Integer complexThreshold, Integer maxLateDays) {
        // 默认参数兜底
        if (passThreshold == null) passThreshold = 0.6d;
        if (complexThreshold == null) complexThreshold = 120;
        if (maxLateDays == null) maxLateDays = 7;
        
        
        Map<String, Object> result = dataAggregationMapper.getStudentRawMetrics(studentId, passThreshold, complexThreshold, maxLateDays);
        
        // MyBatis在所有列值都是NULL时会返回null，我们需要返回空Map
        if (result == null) {
            result = new java.util.HashMap<>();
        } else {
            // 打印所有字段及其值，用于调试
            result.forEach((key, value) -> {
            });
        }
        
        return result;
    }

    @Override
    public TenantEntity getTenantById(String tenantId) {
        // 根据租户ID获取租户信息
        return dataAggregationMapper.getTenantById(tenantId);
    }

    @Override
    public CourseEntity getCourseById(String courseId) {
        // 根据课程ID获取课程信息
        return dataAggregationMapper.getCourseById(courseId);
    }

    @Override
    public List<SubmissionEntity> getStudentSubmissionsByCourse(String studentId, String courseId) {
        return dataAggregationMapper.getStudentSubmissionsByCourse(studentId, courseId);
    }

    @Override
    public List<String> getAllStudentIds() {
        return dataAggregationMapper.getAllStudentIds();
    }

    @Override
    public Map<String, Double> getCourseTotalScores() {
        List<Map<String, Object>> results = dataAggregationMapper.getCourseTotalScores();
        return results.stream()
                .collect(Collectors.toMap(
                        record -> (String) record.get("course_id"),
                        record -> ((Number) record.get("total_full_score")).doubleValue()
                ));
    }

    @Override
    public List<String> getHardSkillTags() {
        return dataAggregationMapper.getHardSkillTags();
    }

    @Override
    public Boolean isTeacherRecommended(String studentId) {
        try {
            Integer count = dataAggregationMapper.countTeacherRecommended(studentId);
            return count != null && count > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public Boolean isCoreTaskTop30(String studentId) {
        try {
            Boolean result = dataAggregationMapper.isCoreTaskTop30(studentId);
            return result != null && result;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public CoreSubmissionVO getCoreSubmission(String studentId) {
        try {
            // 直接调用mapper获取VO，无需转换
            return dataAggregationMapper.getCoreSubmission(studentId);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public Integer countStudentsByMajor(String tenantId, String major) {
        try {
            Integer count = dataAggregationMapper.countStudentsByMajor(tenantId, major);
            return count != null ? count : 0;
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public String getTenantNameByUserId(String userId) {
        try {
            return dataAggregationMapper.getTenantNameByUserId(userId);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public int addFocusMark(String userId, String studentId, Integer tag) {
        // 参数验证
        if (userId == null || studentId == null) {
            throw new IllegalArgumentException("用户ID和学生ID不能为空");
        }

        // 设置默认标签为一般关注(0)
        if (tag == null) {
            tag = 0;
        }

        // 创建关注标记实体
        StudentFocusMarkEntity focusMark = new StudentFocusMarkEntity();
        focusMark.setId(generateId()); // 生成UUID
        focusMark.setUserId(userId);
        focusMark.setStudentId(studentId);
        focusMark.setTag(tag);
        focusMark.setMarkedTime(LocalDateTime.now());

        return dataAggregationMapper.insertFocusMark(focusMark);
    }

    @Override
    public int removeFocusMark(String userId, String studentId) {
        // 参数验证
        if (userId == null || studentId == null) {
            throw new IllegalArgumentException("用户ID和学生ID不能为空");
        }

        return dataAggregationMapper.deleteFocusMark(userId, studentId);
    }

    @Override
    public StudentFocusMarkEntity getFocusMark(String userId, String studentId) {
        if (userId == null || studentId == null) {
            return null;
        }
        return dataAggregationMapper.getFocusMark(userId, studentId);
    }

    // 生成UUID的工具方法
    private String generateId() {
        return UUID.randomUUID().toString();
    }

    // 获取任务信息
    @Override
    public AssignmentEntity getAssignmentInfo(String assignmentId) {
        return dataAggregationMapper.getAssignmentInfo(assignmentId);
    }

    @Override
    public Long countAllStudents() {
        try {
            return dataAggregationMapper.countAllStudents();
        } catch (Exception e) {
            return 0L;
        }
    }

    @Override
    public List<UserEntity> getStudentsWithPagination(int offset, int size) {
        try {
            return dataAggregationMapper.getStudentsWithPagination(offset, size);
        } catch (Exception e) {
            return Collections.emptyList();
        }
    }

    @Override
    public List<AssignmentEntity> getAssignmentsByIds(List<String> assignmentIds) {
        try {
            if (assignmentIds == null || assignmentIds.isEmpty()) {
                return Collections.emptyList();
            }
            return dataAggregationMapper.getAssignmentsByIds(assignmentIds);
        } catch (Exception e) {
            return Collections.emptyList();
        }
    }

    @Override
    public List<AssignmentEntity> getAllCompletedAssignments() {
        try {
            return dataAggregationMapper.getAllCompletedAssignments();
        } catch (Exception e) {
            return Collections.emptyList();
        }
    }

    @Override
    public Boolean hasHighPotentialSubmission(String studentId) {
        try {
            // 查询高潜力成果标记表，只要有一条记录就返回true
            Integer count = dataAggregationMapper.countHighPotentialSubmissions(studentId);
            return count != null && count > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public CoreSubmissionVO getCoreSubmissionByAssignmentId(String studentId, String assignmentId) {
        try {
            return dataAggregationMapper.getCoreSubmissionByAssignmentId(studentId, assignmentId);
        } catch (Exception e) {
            log.error("根据任务ID获取核心成果失败, studentId: {}, assignmentId: {}", studentId, assignmentId, e);
            return null;
        }
    }
}